import java.util.*;

public class demo1 {
    public static class o{
        String key;
        Integer values;

        public o(String key, Integer value) {
            this.key=key;
            this.values=value;
        }

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }

        public Integer getValues() {
            return values;
        }

        public void setValues(Integer values) {
            this.values = values;
        }
    }
    public static List<String> topKFrequent(String[] words, int k) {
        HashMap<String,Integer>map=new HashMap<>();
        for(String temp:words){
            map.put(temp,map.getOrDefault(temp,0)+1);
        }
        PriorityQueue<o>priorityQueue=new PriorityQueue<>(
                ((o1, o2) -> o1.getKey().equals(o2.getKey())?o1.getKey().compareTo(o2.getKey()):
                                o2.getValues()- o1.getValues()
                )
        );
        for(Map.Entry<String,Integer>entry:map.entrySet()){
            o o=new o(entry.getKey(),entry.getValue());
            priorityQueue.add(o);
            if(priorityQueue.size()>k)priorityQueue.poll();
        }
        List<String>list=new ArrayList<>();
        while (!priorityQueue.isEmpty()){
            list.add(priorityQueue.poll().key);
        }
        Collections.reverse(list);
        return list;
    }

    public static void main(String[] args) {
        String[] words=new String[]{"i", "love", "leetcode", "i", "love", "coding"};
        List<String>list=new ArrayList<>();
        list=topKFrequent(words,2);
        System.out.println(Arrays.stream(list.toArray()).toArray());
    }
}
